package com.hvilela;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * @author Henrique de Souza Vilela
 * henrique.vilela@gmail.com
 */
public abstract class Drawer {

	protected int border = 2;

	public final BufferedImage draw(int width, int height, List<Entry> entries) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) image.getGraphics();

		g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

		g.setColor(Color.WHITE);
		g.fillRect(0, 0, image.getWidth(), image.getHeight());

		draw(image, entries);

		return image;
	}

	public abstract BufferedImage draw(BufferedImage image, List<Entry> entries);

	protected final void draw(BufferedImage image, Entry entry, int x, int y, int width, int height) throws IOException {
		entry.setPosition(new Point(x, y));
		entry.setArea(new Dimension(width, height));

		width -= border;
		height -= border;
		x += border;
		y += border;

		BufferedImage entryImage = entry.getImage();

		double destinationRatio = width / (double) height;
		double sourceRatio = entryImage.getWidth() / (double) entryImage.getHeight();

		int newWidth = entryImage.getWidth();
		int newHeight = entryImage.getHeight();

		if (destinationRatio > sourceRatio) {
			newHeight = (int) (newWidth / destinationRatio);
		} else {
			newWidth = (int) (newHeight * destinationRatio);
		}

		int newY = (entryImage.getHeight() - newHeight) / 2;
		int newX = (entryImage.getWidth() - newWidth) / 2;

		Graphics2D graphics = (Graphics2D) image.getGraphics();
		graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics.drawImage(entryImage, x, y, x + width, y + height, newX, newY, newX + newWidth, newY + newHeight, null);
	}
}